<?php

/**
 * 练习
 * User: yoyo
 */

namespace app\modules\app\controllers;

use app\libs\ContentControl;
use app\libs\Method;
use app\modules\app\models\CheckAnswer;
use app\modules\app\models\ExerciseTime;
use app\modules\app\models\QuestionCollect;
use app\modules\app\models\QuestionMark;
use app\modules\cn\models\ExerciseCategory;
use app\modules\cn\models\ExerciseResult;
use app\modules\cn\models\RankingAll;
use app\modules\cn\models\TestResult;
use app\modules\exercise\models\ExerciseList;
use app\modules\exercise\models\ExerciseListDetail;
use app\modules\cn\models\ExerciseList as CnExercise ;
use yii;
use app\libs\AppControl;

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');

class PractiseController extends AppControl
{

    public $enableCsrfValidation = false;

    function init (){
        parent::init();
        include_once($_SERVER['DOCUMENT_ROOT'].'/../libs/ucenter/ucenter.php');
    }

//听力做题列表
    public function actionListenList()
    {
        $catId=\Yii::$app->request->get('catId',422);
        $cate_id_arr = array(413, 424, 435);
        $model = new ExerciseList();
        $data = $model->getListenList($cate_id_arr);
        $data[0][0]=array_values([$data[0][0][8],$data[0][0][9],$data[0][0][10]]);
        $category=$data[0][0];
        $data = $model->listenProgressRate($data[1][0][$catId],$catId);
        die(json_encode(['data' => $data,'category'=>$category,'code'=>1]));
    }

    //听力做题的题目
    public function actionListenExercise()
    {
        $model = new ExerciseList();
        $id = Yii::$app->request->get('id');
        $type = Yii::$app->request->get('type',1);//开始做题重新做题1,2继续和结果做题
        $userId = Yii::$app->session->get('userId');
        if ($userId == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $name=ExerciseList::find()->asArray()->select(['content_id','pid','name','cate_id','cate_id as catId'])->where("content_id=$id")->orderBy('id asc')->one();
        $pids=ExerciseList::find()->asArray()->select(['content_id','pid','name','cate_id','cate_id as catId'])->where('cate_id='.$name['cate_id'].' and name="'.$name['name'].'"')->orderBy('id asc')->all();
        if($pids==false){
            die(json_encode(['message' => '暂无题目!', 'code' => 0]));
        }
        $pids= array_column($pids,'content_id');
        $data['article']=ExerciseList::find()->asArray()->select('*,cate_id as catId,content_id as id')->where("content_id =".$pids[0])->orderBy('content_id asc')->one();
        if ($type == 1) {
            $data['resultid']=time();
            $data['newid']=time();
        } else {
            $pidsStr=implode(',',$pids);
            $data['resultid'] = Yii::$app->db->createCommand("select resultid from {{%ielts_test_result}} where fid=" . $name['catId'] . " and pid in (" . $pidsStr . ") and userid=$userId and answer!='' order by id desc")->queryOne()['resultid'];
            $data['newid'] = Yii::$app->db->createCommand("select newid from {{%ielts_test_result}} where fid=" . $name['catId'] . " and pid in (" . $pidsStr . ") and userid=$userId and answer!='' order by id desc")->queryOne()['newid'];
        }
        foreach($pids as $k =>$v){
            if($v!=false){
                $data['topic'][$k]['parent'] = ExerciseList::find()->asArray()->select('*,cate_id as catId,content_id as id')->where("content_id =".$v)->orderBy('content_id asc')->one();
                $data['topic'][$k]['son'] = ExerciseListDetail::find()->asArray()->select('*,cate_id as catId,content_id as id')->where("pid =".$v)->orderBy('content_id asc')->all();

                foreach($data['topic'][$k]['son'] as $key=>$val){
                    if($v!=false){
                        $data['newid'] = empty($data['newid']) ? "''" : $data['newid'];
                        $tem = Yii::$app->db->createCommand("select pid,result,answer,really from {{%ielts_test_result}} where fid=" . $data['topic'][$k]['parent']['catId'] . " and testid=".$data['topic'][$k]['son'][$key]['id']."  and userid=$userId and answer!=''  and newid=".$data['newid']." order by id desc")->queryOne();
                    }
                    if(!isset($tem)||$tem==false){
                        $data['topic'][$k]['son'][$key]['userAnswer']='';
                    }else{
                        $data['topic'][$k]['son'][$key]['userAnswer'] = $tem['answer'];
                    }
                }
            }
        }
        $data['topic']=$model->listenFormat($data['topic']);
        $data['isCollect'] = QuestionCollect::isCollect(implode(',', $pids), 1);
        $data['mark'] = QuestionMark::getMark(implode(',', $pids), 1);
        $data['code']=1;
        die(json_encode($data));
    }

    //精听
    public function actionListeningIntensive()
    {
        $id = Yii::$app->request->get('id');
        $userId = Yii::$app->session->get('userId');
//        if ($userId == false) {
//            die(json_encode(['message' => '未登录', 'code' => 5]));
//        }
        $data = ExerciseListDetail::find()->asArray()->select(['sencenter', 'problemComplement', 'duration'])->where('pid=' . $id)->orderBy('id asc')->one();
        $listen = ExerciseList::find()->asArray()->select(['listeningFile'])->where('content_id=' . $id)->orderBy('id asc')->one();
        $listen = ExerciseListDetail::getlabeldeletesetences($listen['listeningFile']);
        $listen =  count($listen) > 1 ? $listen[1] : $listen[0];
        $data['problemComplement'] = ExerciseListDetail::getlabeldeletesetences($data['problemComplement']);
        $data['sencenter'] =ExerciseListDetail::getlabeldeletesetences($data['sencenter']);
        $time = explode(',', nl2br($data['duration']));
        static $detail = array();
        foreach ($data['problemComplement'] as $k => $v) {
            $detail[$k]['en'] =  html_entity_decode($v, ENT_QUOTES);
            $detail[$k]['cn'] = trim(trim(str_replace([PHP_EOL,'\r'], '', $data['sencenter'][$k]),PHP_EOL),'\r');
            $detail[$k]['start_time'] = isset($time[2*$k]) ? $time[2*$k] : '';
            $detail[$k]['end_time'] = isset($time[$k*2+1]) ? $time[$k*2+1] : '';
        }
        $data['code'] = 1;
        die(json_encode(['code' => 1, 'data' => ['detail'=>$detail,'count'=>count($detail),'listen'=>$listen!=false?'https://www.thinkuprep.com' .$listen:'']]));
    }


    /**
     * 阅读列表
     * by  yoyo
     */
    public function actionReadList()
    {
        $model = new ExerciseList();
        $catId=\Yii::$app->request->get('catId',473);
        $contentId=ExerciseList::find()->select('name')->asArray()->where("cate_id=".$catId)->distinct()->orderBy('id asc')->all();
        $data=array();
        foreach($contentId as $k=>$v){
            $data[$k]=ExerciseList::find()->select('*,cate_id as catId,content_id as id')->asArray()->where("cate_id=".$catId.' and name="'.$v['name'].'"')->distinct()->orderBy('content_id asc')->one();
        }
        $category=ExerciseCategory::find()->asArray()->select('*,cate_id as id')->where('pid=462 and cate_id>472 ')->all();
        $data = $model->progressRate($data);
        die(json_encode(['data' => $data,'category'=>$category,'code'=>1]));
    }

    //阅读做题的题目 已改
    public function actionReadExercise()
    {
        $model = new ExerciseList();
        $catId = Yii::$app->request->get('catId');
        $name = Yii::$app->request->get('name');
        $type = Yii::$app->request->get('type',1);
        $userId = Yii::$app->session->get('userId');
        if ($userId == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $pids=ExerciseList::find()->asArray()->select(['content_id','pid','name','cate_id as catId'])->where("cate_id=$catId and name='".$name."'")->orderBy('id asc')->all();
        if($pids==false){
            die(json_encode(['message' => '暂无题目!', 'code' => 0]));
        }
        $pids= array_column($pids,'content_id');
        $data['article']=ExerciseList::find()->asArray()->select('*')->where("content_id=$pids[0]")->orderBy('id asc')->one();
        $data['article']['description']=$data['article']['description']!=false?str_replace(PHP_EOL,'',nl2br($data['article']['description'])):'';
        if ($type == 1) {
            Yii::$app->session->set('read-resultid', time());
            Yii::$app->session->set('read-newid', time());
            $data['resultid'] = Yii::$app->session->get('read-resultid');
            $data['newid'] = Yii::$app->session->get('read-newid');
        } else {
            $pidsStr=implode(',',$pids);
            $resultidTem = Yii::$app->db->createCommand("select resultid from {{%ielts_test_result}} where fid=" . $catId . " and pid in(" . $pidsStr . ") and userid=$userId order by id desc")->queryOne()['resultid'];
            $data['resultid'] = $resultidTem==false?time():$resultidTem;
            $newidTem = Yii::$app->db->createCommand("select newid from {{%ielts_test_result}} where fid=" . $catId . " and pid in(" . $pidsStr . ") and userid=$userId order by id desc")->queryOne()['newid'];
            $data['newid']=($newidTem==false?time():$newidTem);
        }
        foreach($pids as $k =>$v){
            if($v!=false){
                $data['topic'][$k]['parent'] = ExerciseList::find()->asArray()->select('*,cate_id as catId,content_id as id')->where("content_id=$v")->one();
                $data['topic'][$k]['son'] = ExerciseListDetail::find()->asArray()->select('*,cate_id as catId,content_id as id')->where("pid=$v")->orderBy('content_id asc')->all();
                foreach($data['topic'][$k]['son'] as $key=>$val){
                    if($v!=false)
                        $tem = Yii::$app->db->createCommand("select pid,result,answer,really from {{%ielts_test_result}} where fid=" . $data['topic'][$k]['parent']['catId'] . " and testid=".$data['topic'][$k]['son'][$key]['content_id']."  and userid=$userId  and resultid=".$data['resultid']." and answer!='' order by id desc")->queryOne();
                    $data['topic'][$k]['son'][$key]['userAnswer'] = (isset($tem)&&$tem!=false)?$tem['answer']:'';
                }
            }
        }
//        $model = new CnExercise();
        $data['topic']= $model->format($data['topic']);
        $data['isCollect'] = QuestionCollect::isCollect(implode(',', $pids), 2);
        $data['mark']=QuestionMark::getMark(implode(',', $pids),2);
        $data['code']=1;
        die(json_encode($data));
    }

    //写作
    public function actionWriteList()
    {
        $model = new ExerciseList();
        $catId = \Yii::$app->request->get('catId', 522);
        $userId = \Yii::$app->session->get('userId');
        $contentId = ExerciseList::find()->select('content_id as id')->asArray()->where("cate_id=" . $catId . " and pid=0")->distinct()->orderBy('id asc')->all();
        $category=ExerciseCategory::find()->select('*,cate_id as catId')->asArray()->where('pid=512 and cate_id>521')->all();
        $tem = $model->spokenProgressRate($contentId,$catId);
        $data=array();
        foreach($tem as $k=>$v){
            $v['isCheck']=0;
            if($userId!=false){
                $tem=Yii::$app->db->createCommand("select resultid,id from {{%ielts_test_result}} where fid=" . $catId . " and pid =" . $v['id'] . " and userId=$userId and ISNULL(answer)=0 and LENGTH(trim(answer))>0 group by resultid order by id desc")->queryOne();
                $checkData= $tem==false?0:CheckAnswer::find()->where('resultId='.$tem['resultid'].' and userid='.$userId.' and typeid=3')->one();
                $v['isCheck']= $checkData==false?0:1;
            }
            if (array_key_exists($v['nameTest'], $data)) {
                $data[$v['nameTest']][] = $v;
            } else {
                $data[$v['nameTest']][] = $v;
            }
        }
        $data=array_values($data);
        die(json_encode(['data' => $data,'category'=>$category,'code'=>1]));
    }

    //写作做题
    public function actionWriteExercise()
    {
        $id = Yii::$app->request->get('id');
        $type = Yii::$app->request->get('type',1);//1开始做题 2重新做题
        $userId = Yii::$app->session->get('userId');
        if ($userId == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $son = ExerciseListDetail::find()->asArray()->where("pid=$id")->all();
        // 查询父类
        $parent = ExerciseList::find()->asArray()->where("content_id=$id")->one();
        $resultId= Yii::$app->db->createCommand("select resultid,newid from {{%ielts_test_result}} where fid=" . $parent['cate_id'] . " and pid =" . $id. " and userid=$userId order by id desc")->queryOne();

        $isCheck =  0;
        if ($resultId==false||$type==2) {
            $resultid =  time();
            $newid =  time();
        } else {
            $resultid = $resultId['resultid'];
            $newidTem = $resultId['newid'];
            $newid=($newidTem==false?time():$newidTem);
            $tem=Yii::$app->db->createCommand("select resultid,id from {{%ielts_test_result}} where fid=" . $parent['cate_id'] . " and pid =" . $parent['content_id'] . " and userId=$userId and ISNULL(answer)=0 and LENGTH(trim(answer))>0 group by resultid order by id desc")->queryOne();
            $checkData= $tem==false?0:CheckAnswer::find()->where('resultId='.$resultid.' and userid='.$userId.' and typeid=3')->one();
            $isCheck= $checkData==false?0:1;
        }
        foreach($son as $k=>$v){
            $tem=TestResult::find()->asArray()->where('pid='.$id.' and testid='.$v['content_id'] ." and userid=$userId and answer !=''")->orderBy('id desc')->one();
            $son[$k]['userAnswer']=$tem!=false?$tem['answer']:'';
        }
        $isCollect = QuestionCollect::isCollect($parent['content_id'], 3);
        $mark = QuestionMark::getMark($parent['content_id'], 3);
        die(json_encode(['parent' => $parent, 'son' => $son[0], 'code' => 1, 'resultid' => $resultid, 'newid' => $newid, 'isCollect' => $isCollect, 'mark' => $mark,'isCheck'=>$isCheck]));
    }
    /**
     * 口语列表
     * by  yoyo
     */
    public function actionSpokenList()
    {
        $cate_id = Yii::$app->request->get('catId',546); // 默认剑雅8 546
        $userId = Yii::$app->session->get('userId'); // 默认剑雅8 546
        $cate_model = new ExerciseCategory();
        $datalist = $cate_model->getSpeakCateList($cate_id);//分类
        // 删除剑雅5、剑雅6、剑雅7 剑雅11
        $datalist=array_values([$datalist[7],$datalist[8],$datalist[9]]);
        $cate_list = ExerciseList::find()->select('id,cate_id,cate_id as catId,content_id,name,title,image,viewCount,catName,title_image')->where(['cate_id'=>$cate_id])->asArray()->all();//当前分类下的数据
        $list = [];
        if ($cate_list) {
            foreach ($cate_list as $key => $value) {
                //是不是做过,然后是否核对了
                $isCheck=0;
                if($userId!=false){
                    $tem=Yii::$app->db->createCommand("select resultid,id from {{%ielts_test_result}} where fid=" . $value['catId'] . " and pid =" . $value['content_id'] . " and userId=$userId and ISNULL(answer)=0 and LENGTH(trim(answer))>0 group by resultid order by id desc")->queryOne();
                    $checkData= $tem==false?0:CheckAnswer::find()->where('resultId='.$tem['resultid'].' and userid='.$userId.' and typeid=4')->one();
                    $isCheck= $checkData==false?0:1;
                }
                $tmp = explode('-', $value['name']);
                $cate_list[$key]['test_name'] = substr(trim($value['name']),0, -6);
                $cate_list[$key]['part_name'] = substr(trim($value['name']), -5);
                $cate_list[$key]['isCheck'] = $isCheck;
            }
            $list = $cate_list;
        }

        $res = [];
        foreach ($list as $key => $value) {
            if (array_key_exists($value['test_name'], $res)) {
                $res[$value['test_name']][] = $value;
            } else {
                $res[$value['test_name']][] = $list[$key];
            }
        }
        $res=array_values($res);
       die(json_encode(['type' =>4, 'typename' =>'口语练习', 'category' => $datalist, 'data' => $res, 'cate_id' => $cate_id, 'code'=>1]));
    }

    //口语做题的题目
    public function actionSpokenExercise()
    {
        $id = Yii::$app->request->get('id');
        $type = Yii::$app->request->get('type',1);//开始1 重新2
        $userId = Yii::$app->session->get('userId');
        if ($userId == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $son = ExerciseListDetail::find()->select('*,content_id as id')->asArray()->where("pid=$id")->all();
        // 查询父类
        $parent = ExerciseList::find()->asArray()->select('*,content_id as id,cate_id as catId,item as description')->where("content_id=$id")->one();
        $resultId= Yii::$app->db->createCommand("select resultid,newid from {{%ielts_test_result}} where fid=" . $parent['cate_id'] . " and pid =" . $id. " and userid=$userId order by id desc")->queryOne();
        if ($resultId == false || $type == 2) {
            $resultid =  time();
            $newid =  time();
        } else {
            $resultid = $resultId['resultid'];
            $newidTem = $resultId['newid'];
            $newid=($newidTem==false?time():$newidTem);
        }
        $list=[];
        foreach($son as $k=>$v){
            if($type==2){
                $son[$k]['userAnswer']='';
                $son[$k]['answerliked']=0;
                $son[$k]['answerId']='';
                $son[$k]['time']=0;
            }else{
                $answerTem=TestResult::find()->asArray()->where('pid='.$id.' and testid='.$v['id'].' and userid='.$userId .' and answer !=""')->orderBy('id desc')->one();
                $son[$k]['userAnswer']=$answerTem!=false?$answerTem['answer']:'';
                $son[$k]['answerliked']=$answerTem!=false?$answerTem['like']:0;
                $son[$k]['answerId']=$answerTem!=false?$answerTem['id']:'';
                $son[$k]['time']=$answerTem!=false?$answerTem['time']:0;
            }
            $tem=TestResult::find()->asArray()->select(['x2_user.userName','x2_user.image','x2_ielts_test_result.*'])->where('pid='.$id.' and testid='.$v['id']." and answer !=''")->leftJoin("x2_user",'x2_user.id=x2_ielts_test_result.userId')->orderBy('like desc')->limit(10)->all();
            $list[$k]=$tem!=false?$tem:array();
        }
        $isCollect = QuestionCollect::isCollect($parent['content_id'], 4);
        $mark = QuestionMark::getMark($parent['content_id'], 4);
        die(json_encode(['parent' => $parent, 'son' => $son, 'list' => $list, 'code' => 1, 'resultid' => $resultid, 'newid' => $newid, 'isCollect'=>$isCollect,'mark'=>$mark]));
    }

    //保存阅读做题数据
    public function actionSaveReadAnswer()
    {
        $userId = Yii::$app->session->get('userId');
        if ($userId == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $model = new ExerciseResult();
        $model->testid = $testid = Yii::$app->request->post('testid');//小题的id
        $model->fid = $fid = Yii::$app->request->post('fid');//分类的id
        $model->pid = $pid = Yii::$app->request->post('pid');//pid
        $model->resultid = $resultid = Yii::$app->request->post('resultid');//同一次做题的id
        $model->newid = $newid = Yii::$app->request->post('newid');//同一次做题的id
        $model->answer = $answer = rtrim(ltrim(Yii::$app->request->post('answer')));//用户答案
        $model->really = $really = trim(Yii::$app->request->post('really'));//正确答案
        $model->result = $result = 0;
        $model->userid = $userId;
        $model->typeid = Yii::$app->request->post('typeid',2);
        $model->time = Yii::$app->request->post('time');
        $model->createtime = time();
        $model->source = 2;
        $answer = strtolower(ExerciseResult::romanNumber($answer));
        $really = strtolower(ExerciseResult::romanNumber($really));
        if ($answer == $really) {
            $model->result = $result = 1;
        } else {
            $answerData = explode('|', str_replace([' | ',' |','| '],'|',$really));
            if (in_array($answer, $answerData)) {
                $model->result = $result =  1;
            }
        }
        $sign = ExerciseResult::find()->asArray()->where("testid=$testid and userid=$userId AND resultid=$resultid and newid=$newid")->one();
        if ($sign) {
            if($sign['answer']== $model->answer){
                die(json_encode(['message' => '保存成功', 'code' => 1]));
            }
            $data=['answer' => $model->answer];
            if($model->time!=$sign['time']) $data=['answer' => $model->answer,'time'=>$model->time];
            $re = $model->updateAll($data, "userid=$userId and $resultid=$resultid and testid=$testid and newid=$newid");
        } else {
            $re = $model->save();
        }
        $contentModel = new RankingAll();
        $contentModel->getlistentestorder($model->typeid);
        if($re){
            die(json_encode(['message' => '保存成功', 'code' => 1]));
        }
        die(json_encode(['message' => '保存失败', 'code' => 0]));
    }

    /**
     * 添加题目注释,还有去题目处添加
     * by  yoyo
     */
    public function actionAddMark()
    {
        $remark = strip_tags(Yii::$app->request->post('mark'));
        $qid = Yii::$app->request->post('qid');
        $typeid = Yii::$app->request->post('typeid',1);
        $catId = Yii::$app->request->post('catId');
        $uid = Yii::$app->session->get('uid');
        $data = QuestionMark::find()->asArray()->where('qid=' . $qid . ' and uid=' . $uid)->one();
        if ($data == false) {
            $model = new QuestionMark();
            $model->uid = $uid;
            $model->qid = $qid;
            $model->catId = $catId;
            $model->remark = $remark;
            $model->typeid = $typeid;
            $model->createTime = time();
            $re = $model->save();
        } else {
            $re = QuestionMark::updateAll(['remark' => $remark], 'qid=' . $qid . ' and uid=' . $uid);
        }
        if($re==1){
            die(Method::jsonGenerate(1,[],'success'));
        }else{
            die(Method::jsonGenerate(0,[],'失败'));

        }
    }

    /**
     * 笔记列表
     * by  yoyo
     */
    public function actionRemarkList()
    {
        $page = Yii::$app->request->post('page',1);
        $pageSize = Yii::$app->request->post('pageSize',10);
        $typeid = Yii::$app->request->post('typeid');
        $uid = Yii::$app->session->get('uid');
        $offset = ($page - 1) * $pageSize;
        $where='uid='.$uid;
        if($typeid!=false){
            $where.=' and typeid='.$typeid;
            if($typeid==1){
                $where.=' and catId in (422,423,700)';
            }
            if($typeid==2){
                $where.=' and catId in (473,474,718)';
            }
            if($typeid==3){
                $where.=' and catId in (522,720,721)';
            }
            if($typeid==4){
                $where.=' and catId in (550)';
            }
        }else{
            $where.=' and catId in (422,423,700,473,474,718,522,720,721,550)';
        }
        $data=QuestionMark::find()->distinct()->select('x2_exercise_list.name,x2_user_question_remark.*,x2_user_question_remark.qid as pid')->asArray()->leftjoin('x2_exercise_list','x2_exercise_list.content_id=x2_user_question_remark.qid')->where("$where")->offset($offset)->limit($pageSize)->orderBy('id desc')->all();//获取所有的错题
        foreach($data as $k=>$v){
            if($v['typeid']==1||$v['typeid']==2){
                $data[$k]['description']='';
            }else{
                $tem=ExerciseListDetail::find()->asArray()->where('pid='.$v['qid'])->one();
                $data[$k]['description']=$tem!=false?$tem['description']:'';
            }
        }
        $data=RankingAll::getWrongQuestion($data,0,$pageSize);
        die(Method::jsonGenerate(1,['data'=>$data],'success'));
    }


    /**
     * 添加收藏
     * by  yoyo
     */
    public function actionAddCollect()
    {
        $qid = Yii::$app->request->post('qid');
        $typeid = Yii::$app->request->post('typeid',1);
        $catId = Yii::$app->request->post('catId');
        $uid = Yii::$app->session->get('uid');
        $data = QuestionCollect::find()->asArray()->where('qid=' . $qid . ' and uid=' . $uid)->one();
        if ($data == false) {
            $model = new QuestionCollect();
            $model->uid = $uid;
            $model->qid = $qid;
            $model->catId = $catId;
            $model->typeid = $typeid;
            $model->createTime = time();
            $re = $model->save();
        } else {
            die(Method::jsonGenerate(0,[],'不能重复收藏!'));
        }
        if($re==1){
            die(Method::jsonGenerate(1,[],'success'));
        }else{
            die(Method::jsonGenerate(0,[],'失败'));

        }
    }

    /**
     * 删除收藏
     * by  yoyo
     */
    public function actionDeleteCollect()
    {
        $qid = Yii::$app->request->post('qid');
        $uid = Yii::$app->session->get('uid');
        $data = QuestionCollect::find()->asArray()->where('qid=' . $qid . ' and uid=' . $uid)->one();
        if ($data != false) {
            $re=QuestionCollect::deleteAll('qid=' . $qid . ' and uid=' . $uid);
        } else {
            die(Method::jsonGenerate(0,[],'没有收藏数据!'));
        }
        if($re>0){
            die(Method::jsonGenerate(1,[],'success'));
        }else{
            die(Method::jsonGenerate(0,[],'失败'));

        }
    }
    //核对的接口 根据什么来判定是不是核对 听说分类 uid 做题时间来判断
    public function actionCheckAnswer()
    {
        $resultid = Yii::$app->request->post('resultid');
        $typeid = Yii::$app->request->post('typeid');
        $userid = Yii::$app->session->get('userId');
        $data = CheckAnswer::find()->asArray()->where('resultid=' . $resultid . ' and userid=' . $userid.' and typeid='.$typeid)->one();
        if ($data == false) {
            $model = new CheckAnswer();
            $model->userid = $userid;
            $model->resultid = $resultid;
            $model->typeid = $typeid;
            $model->createTime = time();
            $re = $model->save();
        }
        die(Method::jsonGenerate(1,[],'成功!'));
    }

    /**
     * 我的练习记录
     * by  yoyo
     */
    public function actionMyExercise()
    {
        $typeid = Yii::$app->request->post('typeid', 1);
        $userId = Yii::$app->session->get("userId");
        $page = Yii::$app->request->post("page",1);
        $pageSize = Yii::$app->request->post("pageSize",10);
        if($userId==false){
            die(json_encode(['code'=>5,'message'=>'未登录']));
        }
        $where='';
        $offset=($page-1)*$pageSize;
        if($typeid==1){
            $where=' and fid in (422,423,700)';
        }
        if($typeid==2){
            $where=' and fid in (473,474,718)';
        }
        if($typeid==3){
            $where=' and fid in (522,720,721)';
        }
        if($typeid==4){
            $where=' and fid in (550)';
        }
        $sign = ExerciseResult::find()->distinct()->select(['fid','name'])->asArray()->leftJoin('x2_exercise_list','x2_exercise_list.content_id=x2_ielts_test_result.pid')->where("typeid=$typeid and x2_ielts_test_result.userid=$userId and LENGTH(trim(x2_ielts_test_result.pid))>0 and (fid!=false or fid is not null)  $where ")->orderBy('x2_ielts_test_result.id desc')->offset("$offset")->limit("$pageSize")->all();//做题的进度
        $data=array();
        foreach($sign as $k=>$v){
            $data[$k] = ExerciseList::find()->asArray()->select(['name','content_id as id','cate_id as catId'])->orderBy('id desc')->where('name ="' . $v['name'].'" and cate_id='.$v['fid'])->orderBy('content_id')->one();
            $name = ExerciseList::find()->asArray()->select(['name','catName'])->where('cate_id='.$v['fid'])->one();
            $tem = ExerciseList::find()->asArray()->select('content_id')->where('name ="' . $data[$k]['name'].'" and cate_id='.$v['fid'])->all();
            $nameTem=str_replace(' - ','-',str_replace('剑雅', 'jy', $data[$k]['name']));
            $data[$k]['showName'] = $name['catName'].' '.substr($nameTem,strrpos($nameTem,'-')-5);
            $pids = implode(',',array_column($tem,'content_id'));
            $data[$k]['count'] = count(ExerciseListDetail::find()->asArray()->select('id')->where('pid in (' . $pids.')')->all());
//            $newid=ExerciseResult::find()->distinct()->select(['newid'])->asArray()->where("typeid=$typeid and userid=$userId and answer!='' and fid=".$v['fid'])->groupBy('newid')->orderBy('id desc')->one();
            $result=ExerciseResult::find()->distinct()->select(['resultid'])->asArray()->where("typeid=$typeid and userid=$userId and answer!='' and pid in (".$pids.')')->groupBy('resultid')->orderBy('id desc')->one();
            $record = $result!=false?Yii::$app->db->createCommand("select id from {{%ielts_test_result}} where fid=" .$v['fid'] . " and pid in (" . $pids . ") and userid=$userId and resultid=" . $result['resultid'] . " and answer!='' order by id desc")->queryAll():'';
            $data[$k]['isCheck'] = ($result!=false?CheckAnswer::find()->asArray()->where('resultid=' . $result['resultid'] . ' and userid=' . $userId.' and typeid='.$typeid)->one():0)==false?0:1;
            if ($data[$k]['count'] <= count($record)) {//数目相同，表示本章节完成
                $data[$k]['isOver'] = 1;
                $data[$k]['continue'] = 0;

            } else {//继续做题
                $data[$k]['isOver'] = 0;
                $data[$k]['continue'] = 1;
            }
            $data[$k]['userFinish']= count($record);

        }
        die(json_encode(['data'=>$data,'code'=>1]));

    }

    /**
     * 错题本 没有进度
     * by  yoyo
     */
    public function actionWrongQuestion()
    {
        $typeid = Yii::$app->request->post('typeid',1);
        $catId = Yii::$app->request->post('catId');
        $page = Yii::$app->request->post('page',1);
        $pageSize = Yii::$app->request->post('pageSize',10);
        $userId = Yii::$app->session->get('userId');
        $offset = ($page - 1) * $pageSize;
        $where='x2_ielts_test_result.testid is not null and x2_ielts_test_result.userid='.$userId.' and result=0';
        if ($typeid != false) {
            $where.=' and x2_user_check_answer.typeid='.$typeid;
            if($typeid==1){
                $where.=' and x2_exercise_list.cate_id in (422,423,700)';
            }
            if($typeid==2){
                $where.=' and x2_exercise_list.cate_id in (473,474,718)';
            }
        }else{
            $where.=' and (x2_user_check_answer.typeid=1 or x2_user_check_answer.typeid=2)  and x2_exercise_list.cate_id in (422,423,700,473,474,718)';
        }
        $data=  CheckAnswer::find()->asArray()->distinct()->select('x2_ielts_test_result.typeid,x2_exercise_list.name,x2_exercise_list.cate_id as catId')->leftJoin('x2_ielts_test_result','x2_ielts_test_result.newid=x2_user_check_answer.resultid')->leftJoin('x2_exercise_list','x2_exercise_list.content_id=x2_ielts_test_result.pid')->where($where)->orderBy('x2_user_check_answer.id desc')->all();
        foreach($data as $k=>$v){
            $tem=ExerciseList::find()->asArray()->where('name="'.$v['name'].'" and cate_id='.$v['catId'])->orderBy('id asc')->one();
            $data[$k]['content_id']=$data[$k]['pid']=$tem['content_id'];
            $tem=ExerciseList::find()->asArray()->where('name="'.$v['name'].'" and cate_id='.$v['catId'])->orderBy('id asc')->all();
            $pids = implode(',',array_column($tem,'content_id'));
            $result=ExerciseResult::find()->distinct()->select(['resultid'])->asArray()->where("typeid=$typeid and userid=$userId and answer!='' and pid in (".$pids.')')->orderBy('id desc')->one();
            $data[$k]['resultid']= $result!=false?$result['resultid']:'';
            $data[$k]['count']= $data[$k]['content_id']!=false?ExerciseListDetail::find()->asArray()->where('pid in ('.$pids.')')->count():0;
            $right= $result['resultid']!=false?RankingAll::find()->asArray()->where('resultid='.$result['resultid'].' and result=1')->count():0;
            $data[$k]['wrong']= $data[$k]['count']>0?$data[$k]['count']-$right:0;
        }
        $data=RankingAll::getWrongQuestion($data,$offset,$pageSize);
        die(Method::jsonGenerate(1,['data'=>$data],'success'));
    }
    /**
     * 上传作文的做题数据
     * by  yoyo
     */
    public function actionUpSpokenAudio()
    {
        $file = $_FILES['upload'];
        $userId = Yii::$app->session->get('userId');
        if ($userId == false) {
            $re = ['code' => 2, 'message' => '用户未登录'];
            die(json_encode($re));
        }
        $upload = new \UploadFile();
        $upload->int_max_size = 2097152;
        $upload->arr_allow_exts = array('mp3');
        $upload->str_save_path = Yii::$app->params['upSpoken'];
        $arr_rs = $upload->upload($file);
        if ($arr_rs['int_code'] == 1) {
            $filePath = '/' . Yii::$app->params['upSpoken'] . $arr_rs['arr_data']['arr_data'][0]['savename'];
            $res['code'] = 1;
            $res['message'] = '上传成功';
            $res['file'] = $filePath;
        } else {
            $res['code'] = 0;
            $res['message'] = '上传失败，请重试';
        }
        die(json_encode($res));

    }

    //删除口语
    public function actionDeleteSpokenAnswer()
    {
        $userId = Yii::$app->session->get('userId');
        $id = Yii::$app->request->get('id');
        if ($userId == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $data=TestResult::find()->asArray()->where('id='.$id.' and userid='.$userId)->one();
        if ($data==false) {
            die(json_encode(['message' => '用户数据不存在', 'code' => 0]));
        }else{
            $res = TestResult::updateAll(['answer' => ''], "id=$id");
            if ($res==false) {
                die(json_encode(['message' => '删除失败', 'code' => 0]));
            }
            die(json_encode(['message' => '删除成功', 'code' => 1]));
        }

    }
    //口语点赞
    public function actionSpokenLike()
    {
        $id = Yii::$app->request->get('id');
        $data=TestResult::find()->asArray()->where('id='.$id)->one();
        $res = TestResult::updateAll(['like' => ($data['like'] + 1)], "id=$id");
        if ($res) {
            die(json_encode(['message' => '点赞成功', 'code' => 1]));
        }else{
            die(json_encode(['message' => '点赞失败', 'code' => 0]));
        }
    }

    /**
     * 关注列表
     * by  yoyo
     */
    public function actionCollectList()
    {
        $page = Yii::$app->request->post('page',1);
        $pageSize = Yii::$app->request->post('pageSize',10);
        $typeid = Yii::$app->request->post('typeid');
        $uid = Yii::$app->session->get('uid');
        $where='uid='.$uid;
        $offset = ($page - 1) * $pageSize;
        if($typeid!=false){
            $where.=' and typeid='.$typeid;
            if($typeid==1){
                $where.=' and catId in (422,423,700)';
            }
            if($typeid==2){
                $where.=' and catId in (473,474,718)';
            }
            if($typeid==3){
                $where.=' and catId in (522,720,721)';
            }
            if($typeid==4){
                $where.=' and catId in (550)';
            }
        }else{
            $where.=' and catId in (422,423,700,473,474,718,522,720,721,550)';
        }
        $data=QuestionCollect::find()->distinct()->select('x2_exercise_list.name,x2_user_question_collect.*,x2_user_question_collect.qid as pid')->asArray()->leftjoin('x2_exercise_list','x2_exercise_list.content_id=x2_user_question_collect.qid')->where("$where")->offset($offset)->limit($pageSize)->orderBy('id desc')->all();//获取所有的错题
        foreach($data as $k=>$v){
            if ($v['typeid'] == 1 || $v['typeid'] == 2) {
                $data[$k]['description']='';
            }else{
                $tem=ExerciseListDetail::find()->asArray()->where('pid='.$v['qid'])->one();
                $data[$k]['description']=$tem!=false?$tem['description']:'';
            }
        }
        $data=RankingAll::getWrongQuestion($data,0,$pageSize);
        die(Method::jsonGenerate(1,['data'=>$data],'success'));
    }

    /**
     * 做题报告
     */
    public function actionExerciseReport()
    {
        $uid = Yii::$app->session->get('uid');
        $count=RankingAll::getQuestionCount();//总题数
        $rate=RankingAll::getQuestionRate();//一周的正确率
        $tem=ExerciseTime::getTime();//每天的做题时间
        $avgTime= $tem['avgTime'];
        unset($tem['avgTime']);
        $time=$tem;//一周的正确率
        $sumTime=ExerciseTime::getAllTime();//正确百分比
        $startTime=ExerciseTime::find()->asArray()->where("uid=$uid")->orderBy('time asc')->one();
        //循环查找7天的做题数据
        die(Method::jsonGenerate(1,['count'=>$count,'avgTime'=>$avgTime,'rate'=>$rate,'time'=>$time,'sumTime'=>$sumTime,'startTime'=>$startTime],'success'));
    }

    /**
     * 上传做题时间
     */
    public function actionExerciseTime()
    {
        $reData['listen'] = Yii::$app->request->post('listen');
        $reData['spoken'] = Yii::$app->request->post('spoken');
        $reData['read'] = Yii::$app->request->post('read');
        $reData['write'] = Yii::$app->request->post('write');
        $reData['uid'] = Yii::$app->session->get('uid');
        $reData['time'] = Yii::$app->request->post('time');//做题的日期
        $reData['createTime'] =time();//做题的日期
//        $reData['status'] = 0;// 0表示未处理，1表示属实，2表示不属实
        $re = Yii::$app->db->createCommand()->insert("{{%exercise_time}}", $reData)->execute();
        if ($re) {
            die(Method::jsonGenerate(1,[],'success'));
        } else {
            die(Method::jsonGenerate(0,[],'发表失败'));
        }
    }
}
